<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskRewards"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.locale.LocaleText"%>
<%@page import="fi.foyt.cs.controller.LocaleController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.locale.LocaleElement"%>
<%@page import="org.apache.commons.lang3.StringUtils"%>
<%@page import="java.util.Locale"%>
<%@page import="java.util.List"%>
<%@page import="fi.foyt.cs.Settings"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTask"%>
<%@page import="fi.foyt.cs.controller.TaskController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskType"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <jsp:include page="../fragments/head.jsp"></jsp:include>
  <script type="text/javascript">
    function openTaskLevels(taskId) {
      var dialogContent = new Element("div", {className: "genericTasksLevelsDialog"});
      dialogContent.update('<iframe src="generictasks_levels.jsp?taskId=' + taskId + '" width="100%" height="400" frameBorder="0"/>');
      
      var dialog = new S2.UI.Dialog(dialogContent, {
        title: 'Levels',
        buttons: [{
          label: 'Save',
          primary: true,
          action: function(instance) {
            instance.close();
            
            var iframe = dialogContent.down('iframe');
            iframe.contentWindow.save.call(iframe.contentWindow);
          }
        }, {
          label: 'Cancel',
          action: function(instance) {
            instance.close();
          }
        }]
      });
      dialog.open();
    }
  </script>
</head>
<body>
	<jsp:include page="../fragments/header.jsp"></jsp:include>

	<c:set var="taskTypes" value="<%=TaskType.values()%>" />
	<%
	  TaskController taskController = new TaskController();
    LocaleController localeController = new LocaleController();  
	  
	  List<Locale> supportedLocales = Settings.getSupportedLocales();

	  if ("POST".equals(request.getMethod())) {
	    int taskCount = Integer.parseInt(request.getParameter("taskCount"));
	    for (int i = 0; i < taskCount; i++) {
	      Long id = Long.parseLong(request.getParameter("task." + i + ".id"));
        TaskType taskType = TaskType.valueOf(request.getParameter("task." + i + ".taskType"));
        String icon = request.getParameter("task." + i + ".icon");

	      GeneralTask generalTask = taskController.findGeneralTaskById(id);
	      LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
        
	      boolean delete = true;
	      for (Locale locale : supportedLocales) {
	        String name = request.getParameter("task." + i + ".name_" + locale.getLanguage());
	        if (!StringUtils.isBlank(name)) {
	          LocaleText localeText = localeController.findLocaleTextByLocaleElementAndLocale(localeElement, locale);    
	          
	          if (localeText != null) {
	            localeController.updateLocaleText(localeText, name);
	          } else {
	            localeController.createLocaleText(localeElement, locale, name);
	          }

	          delete = false;
	        }
	      }
	      
	      if (delete) {
          taskController.deleteGeneralTask(generalTask);
	      } else {
	        taskController.updateGeneralTaskType(generalTask, taskType);
	        taskController.updateGeneralTaskIcon(generalTask, icon);
	      }
	    }

	    boolean create = false;
      for (Locale locale : supportedLocales) {
        String name = request.getParameter("task.-1.name_" + locale.getLanguage());
        if (!StringUtils.isBlank(name))
          create = true;
      }
      
      if (create) {
        TaskType newType = TaskType.valueOf(request.getParameter("task.-1.taskType"));
        String icon = request.getParameter("task.-1.icon");
        LocaleElement localeElement = localeController.createLocaleElement();
        taskController.createGenaralTask(newType, localeElement, icon);
        
        for (Locale locale : supportedLocales) {
          String name = request.getParameter("task.-1.name_" + locale.getLanguage());
          if (!StringUtils.isBlank(name)) {
            localeController.createLocaleText(localeElement, locale, name);
          }
        }
      }
	  }

	  pageContext.setAttribute("supportedLocales", supportedLocales);
	  pageContext.setAttribute("generalTasks", taskController.listGeneralTasks());
	%>

	<h1>Generic Tasks</h1>

	<form method="POST">
		<input type="hidden" name="taskCount" value="${fn:length(generalTasks)}" />

		<table>
			<tr>
			  <c:forEach items="${supportedLocales}" var="supportedLocale">
          <th>Name - ${supportedLocale}</th>
			  </c:forEach>
				<th>Type</th>
        <th>Icon</th>
				<th>Level</th>
			</tr>

			<c:set var="taskIndex" value="0" />

			<c:forEach items="${generalTasks}" var="generalTask">
				<input type="hidden" name="task.${taskIndex}.id" value="${generalTask.id.id}" />
				<tr>
          <c:forEach items="${supportedLocales}" var="supportedLocale">
            <%
              GeneralTask generalTask = (GeneralTask) pageContext.getAttribute("generalTask");
              LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
              LocaleText localeText = localeController.findLocaleTextByLocaleElementAndLocale(localeElement, (Locale) pageContext.getAttribute("supportedLocale"));
              if (localeText != null)
                pageContext.setAttribute("name", localeText.getText());
            %> 
             
				    <td><input type="text" value="${name}" name="task.${taskIndex}.name_${supportedLocale}" /></td>
          </c:forEach>
					<td><select name="task.${taskIndex}.taskType">
							<c:forEach items="${taskTypes}" var="taskType">
								<c:choose>
									<c:when test="${taskType eq generalTask.taskType}">
										<option value="${taskType}" selected="selected">${taskType}</option>
									</c:when>
									<c:otherwise>
										<option value="${taskType}">${taskType}</option>
									</c:otherwise>
								</c:choose>
							</c:forEach>
					</select></td>
					<td><input type="text" value="${generalTask.icon}" name="task.${taskIndex}.icon" /></td>
					<td><a href="javascript:openTaskLevels(${generalTask.id.id});">Levels</a></td>
				</tr>
				<c:set var="taskIndex" value="${taskIndex + 1}" />
			</c:forEach>

			<tr>
        <c:forEach items="${supportedLocales}" var="supportedLocale">
          <td><input type="text" value="${generalTask.name}" name="task.-1.name_${supportedLocale}" /></td>
        </c:forEach>
				<td><select name="task.-1.taskType">
						<c:forEach items="${taskTypes}" var="taskType">
							<c:choose>
								<c:when test="${taskType eq generalTask.taskType}">
									<option value="${taskType}" selected="selected">${taskType}</option>
								</c:when>
								<c:otherwise>
									<option value="${taskType}">${taskType}</option>
								</c:otherwise>
							</c:choose>
						</c:forEach>
				</select></td>
        <td><input type="text" name="task.-1.icon" /></td>
				<td>[ create first ]</td>
			</tr>
		</table>

		<input type="submit" value="Save" />
	</form>

	<jsp:include page="../fragments/footer.jsp"></jsp:include>
</body>
</html>